import React from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Plus,
  Trash2,
  Zap,
  Ship,
  Train,
  Car,
  AlertTriangle,
  Info,
} from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";

// 通用数组编辑器
const StringArrayEditor = ({
  title,
  items = [],
  onUpdate,
  placeholder,
  onAddItem,
  onRemoveItem,
  onChangeItem,
}) => {
  return (
    <div className="space-y-3">
      <Label className="font-medium">{title}</Label>
      <div className="space-y-2">
        {(items || []).map((item, index) => (
          <div key={index} className="flex items-center gap-2">
            <Input
              value={item}
              onChange={(e) => onChangeItem(index, e.target.value)}
              placeholder={placeholder}
            />
            <Button
              variant="ghost"
              size="icon"
              onClick={() => onRemoveItem(index)}
            >
              <Trash2 className="w-4 h-4 text-red-500" />
            </Button>
          </div>
        ))}
      </div>
      {/* <Button variant="outline" size="sm" onClick={onAddItem}>
        <Plus className="w-4 h-4 mr-2" />
        添加条目
      </Button> */}

      <Button
        variant="outline"
        size="sm"
        onClick={(e) => {
          e.stopPropagation(); // 阻止冒泡到父元素
          e.preventDefault(); // 阻止默认行为（如果有）
          onAddItem();
        }}
        className="bg-white"
      >
        <Plus className="w-4 h-4 mr-2" /> 添加条目
      </Button>
    </div>
  );
};

export default function SpecialMeasuresTab({
  scheme,
  crossingPoint,
  onUpdate,
}) {
  // 检查是否需要显示各种专项措施
  const needsPowerOutage =
    crossingPoint?.crossingType === "power_line" ||
    crossingPoint?.requiresPowerOutage ||
    scheme?.constructionMethod?.includes("带电") ||
    scheme?.constructionMethod?.includes("不停电");

  const needsRoadClosure =
    crossingPoint?.crossingType === "highway" ||
    crossingPoint?.requiresRoadClosure;

  const needsTrafficControl =
    crossingPoint?.crossingType === "railway" ||
    crossingPoint?.requiresTrafficControl;

  const needsNavigationControl =
    crossingPoint?.crossingType === "river" ||
    crossingPoint?.requiresNavigationControl;

  const handlePlanUpdate = (planName, field, value) => {
    const currentPlan = scheme[planName] || {};
    const updatedPlan = { ...currentPlan, [field]: value };
    onUpdate(planName, updatedPlan);
  };

  const handleListUpdate = (fieldName, newArray) => {
    onUpdate(fieldName, newArray);
  };

  const handleGroundingWireChange = (index, field, value) => {
    const newPositions = [...(scheme.groundingWirePositions || [])];
    if (!newPositions[index]) {
      newPositions[index] = {
        position: "",
        specification: "不小于25mm²",
        installation_method: "",
      };
    }
    newPositions[index] = { ...newPositions[index], [field]: value };
    onUpdate("groundingWirePositions", newPositions);
  };

  const addGroundingWire = () => {
    const newPositions = [
      ...(scheme.groundingWirePositions || []),
      {
        position: "",
        specification: "不小于25mm²",
        installation_method: "",
      },
    ];
    onUpdate("groundingWirePositions", newPositions);
  };

  const removeGroundingWire = (index) => {
    const newPositions = (scheme.groundingWirePositions || []).filter(
      (_, i) => i !== index
    );
    onUpdate("groundingWirePositions", newPositions);
  };

  const handleSpecialRequirementToggle = (requirementType, checked) => {
    if (!crossingPoint) return;

    // 这里可以添加逻辑来更新跨越点的特殊要求标志
    // 由于我们只能更新scheme，我们在scheme层面记录这些需求
    const updatedRequirements = {
      ...scheme.specialRequirementsConfig,
      [requirementType]: checked,
    };
    onUpdate("specialRequirementsConfig", updatedRequirements);
  };

  // 如果没有跨越点，显示提示
  if (!crossingPoint) {
    return (
      <div className="p-6 text-center text-gray-500">
        <AlertTriangle className="w-12 h-12 mx-auto mb-3 text-gray-400" />
        <h3 className="text-lg font-medium text-gray-600 mb-2">无关联跨越点</h3>
        <p>
          请先关联一个跨越点以配置专项措施。专项措施会根据跨越点类型自动显示相应的配置选项。
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 专项措施需求配置 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Info className="w-5 h-5 text-blue-600" />
            专项措施需求配置
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Alert>
            <Info className="h-4 w-4" />
            <AlertDescription>
              根据跨越点类型 <strong>{crossingPoint.crossingType}</strong>{" "}
              和施工方法，系统会自动显示相应的专项措施配置。
              您也可以手动启用其他专项措施。
            </AlertDescription>
          </Alert>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="power-outage"
                checked={
                  needsPowerOutage ||
                  scheme.specialRequirementsConfig?.powerOutage
                }
                onCheckedChange={(checked) =>
                  handleSpecialRequirementToggle("powerOutage", checked)
                }
              />
              <Label htmlFor="power-outage" className="flex items-center gap-2">
                <Zap className="w-4 h-4 text-yellow-600" />
                需要停电作业措施
              </Label>
            </div>

            <div className="flex items-center space-x-2">
              <Checkbox
                id="road-closure"
                checked={
                  needsRoadClosure ||
                  scheme.specialRequirementsConfig?.road_closure
                }
                onCheckedChange={(checked) =>
                  handleSpecialRequirementToggle("road_closure", checked)
                }
              />
              <Label htmlFor="road-closure" className="flex items-center gap-2">
                <Car className="w-4 h-4 text-orange-600" />
                需要封路措施
              </Label>
            </div>

            <div className="flex items-center space-x-2">
              <Checkbox
                id="traffic-control"
                checked={
                  needsTrafficControl ||
                  scheme.specialRequirementsConfig?.traffic_control
                }
                onCheckedChange={(checked) =>
                  handleSpecialRequirementToggle("traffic_control", checked)
                }
              />
              <Label
                htmlFor="traffic-control"
                className="flex items-center gap-2"
              >
                <Train className="w-4 h-4 text-blue-600" />
                需要交通管制措施
              </Label>
            </div>

            <div className="flex items-center space-x-2">
              <Checkbox
                id="navigation-control"
                checked={
                  needsNavigationControl ||
                  scheme.specialRequirementsConfig?.navigationControl
                }
                onCheckedChange={(checked) =>
                  handleSpecialRequirementToggle("navigationControl", checked)
                }
              />
              <Label
                htmlFor="navigation-control"
                className="flex items-center gap-2"
              >
                <Ship className="w-4 h-4 text-cyan-600" />
                需要停航措施
              </Label>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 带电跨越-停电措施 */}
      {(needsPowerOutage ||
        scheme.specialRequirementsConfig?.powerOutage) && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Zap className="text-red-500" />
              停电作业专项安全措施
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label htmlFor="powerOutageScope">停电范围</Label>
              <Input
                id="powerOutageScope"
                value={scheme.powerOutageScope || ""}
                onChange={(e) => onUpdate("powerOutageScope", e.target.value)}
                placeholder="例如：110kV某某线#1-#5塔"
              />
            </div>

            <div className="space-y-3">
              <Label className="font-medium">接地线装设位置</Label>
              {(scheme.groundingWirePositions || []).map((gw, index) => (
                <div
                  key={index}
                  className="grid grid-cols-1 md:grid-cols-4 gap-2 p-3 bg-gray-50 rounded-lg border items-center"
                >
                  <Input
                    value={gw.position || ""}
                    onChange={(e) =>
                      handleGroundingWireChange(
                        index,
                        "position",
                        e.target.value
                      )
                    }
                    placeholder="装设位置"
                    className="md:col-span-2"
                  />
                  <Input
                    value={gw.specification || ""}
                    onChange={(e) =>
                      handleGroundingWireChange(
                        index,
                        "specification",
                        e.target.value
                      )
                    }
                    placeholder="规格"
                  />
                  <div className="flex items-center gap-2">
                    <Input
                      value={gw.installation_method || ""}
                      onChange={(e) =>
                        handleGroundingWireChange(
                          index,
                          "installation_method",
                          e.target.value
                        )
                      }
                      placeholder="装设方式"
                    />
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => removeGroundingWire(index)}
                    >
                      <Trash2 className="w-4 h-4 text-red-500" />
                    </Button>
                  </div>
                </div>
              ))}
              <Button variant="outline" size="sm" onClick={addGroundingWire}>
                <Plus className="w-4 h-4 mr-2" />
                添加接地线
              </Button>
            </div>

            <StringArrayEditor
              title="带电跨越专项安全措施"
              items={scheme.liveCrossingSafetyMeasures || []}
              onAddItem={() =>
                handleListUpdate("liveCrossingSafetyMeasures", [
                  ...(scheme.liveCrossingSafetyMeasures || []),
                  "",
                ])
              }
              onChangeItem={(index, value) => {
                const newList = [...(scheme.liveCrossingSafetyMeasures || [])];
                newList[index] = value;
                handleListUpdate("liveCrossingSafetyMeasures", newList);
              }}
              onRemoveItem={(index) =>
                handleListUpdate(
                  "liveCrossingSafetyMeasures",
                  (scheme.liveCrossingSafetyMeasures || []).filter(
                    (_, i) => i !== index
                  )
                )
              }
              placeholder="例如：确认线路已停电并悬挂接地线"
            />
          </CardContent>
        </Card>
      )}

      {/* 公路跨越-封路措施 */}
      {(needsRoadClosure ||
        scheme.specialRequirementsConfig?.road_closure) && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Car className="text-orange-500" />
              公路封路专项计划
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>封路范围</Label>
              <Input
                value={scheme.roadClosurePlan?.closure_scope || ""}
                onChange={(e) =>
                  handlePlanUpdate(
                    "roadClosurePlan",
                    "closure_scope",
                    e.target.value
                  )
                }
                placeholder="例如：XX国道K10+100至K10+500段"
              />
            </div>
            <div>
              <Label>封路时间</Label>
              <Input
                value={scheme.roadClosurePlan?.closure_duration || ""}
                onChange={(e) =>
                  handlePlanUpdate(
                    "roadClosurePlan",
                    "closure_duration",
                    e.target.value
                  )
                }
                placeholder="例如：2024年10月1日 02:00-05:00"
              />
            </div>
            <div>
              <Label>交通疏导方案</Label>
              <Textarea
                value={scheme.roadClosurePlan?.traffic_diversion_plan || ""}
                onChange={(e) =>
                  handlePlanUpdate(
                    "roadClosurePlan",
                    "traffic_diversion_plan",
                    e.target.value
                  )
                }
                placeholder="描述绕行路线、标志设置等"
              />
            </div>
          </CardContent>
        </Card>
      )}

      {/* 铁路跨越-管制措施 */}
      {(needsTrafficControl ||
        scheme.specialRequirementsConfig?.traffic_control) && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Train className="text-blue-500" />
              铁路交通管制专项计划
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>管制范围</Label>
              <Input
                value={scheme.railway_control_plan?.control_scope || ""}
                onChange={(e) =>
                  handlePlanUpdate(
                    "railway_control_plan",
                    "control_scope",
                    e.target.value
                  )
                }
                placeholder="例如：京广线K50+200至K50+800区间"
              />
            </div>
            <div>
              <Label>管制时间（"天窗"点）</Label>
              <Input
                value={scheme.railway_control_plan?.control_duration || ""}
                onChange={(e) =>
                  handlePlanUpdate(
                    "railway_control_plan",
                    "control_duration",
                    e.target.value
                  )
                }
                placeholder="例如：2024年10月2日 01:30-04:30"
              />
            </div>
            <div>
              <Label>列车运行图协调</Label>
              <Textarea
                value={
                  scheme.railway_control_plan?.train_schedule_coordination || ""
                }
                onChange={(e) =>
                  handlePlanUpdate(
                    "railway_control_plan",
                    "train_schedule_coordination",
                    e.target.value
                  )
                }
                placeholder="描述与铁路部门的协调内容"
              />
            </div>
          </CardContent>
        </Card>
      )}

      {/* 河流跨越-停航措施 */}
      {(needsNavigationControl ||
        scheme.specialRequirementsConfig?.navigationControl) && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Ship className="text-cyan-500" />
              航道停航专项计划
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>停航范围</Label>
              <Input
                value={scheme.navigationControlPlan?.control_scope || ""}
                onChange={(e) =>
                  handlePlanUpdate(
                    "navigationControlPlan",
                    "control_scope",
                    e.target.value
                  )
                }
                placeholder="例如：长江航道#301至#305标之间"
              />
            </div>
            <div>
              <Label>停航时间</Label>
              <Input
                value={scheme.navigationControlPlan?.control_duration || ""}
                onChange={(e) =>
                  handlePlanUpdate(
                    "navigationControlPlan",
                    "control_duration",
                    e.target.value
                  )
                }
                placeholder="例如：2024年10月3日 09:00-11:00"
              />
            </div>
            <div>
              <Label>船舶通知方案</Label>
              <Textarea
                value={
                  scheme.navigationControlPlan?.vessel_notification_plan || ""
                }
                onChange={(e) =>
                  handlePlanUpdate(
                    "navigationControlPlan",
                    "vessel_notification_plan",
                    e.target.value
                  )
                }
                placeholder="描述如何通知过往船舶"
              />
            </div>
          </CardContent>
        </Card>
      )}

      {/* 如果没有启用任何专项措施 */}
      {!needsPowerOutage &&
        !needsRoadClosure &&
        !needsTrafficControl &&
        !needsNavigationControl &&
        !scheme.specialRequirementsConfig?.powerOutage &&
        !scheme.specialRequirementsConfig?.road_closure &&
        !scheme.specialRequirementsConfig?.traffic_control &&
        !scheme.specialRequirementsConfig?.navigationControl && (
          <Card>
            <CardContent className="text-center py-8">
              <Info className="w-12 h-12 mx-auto mb-3 text-gray-400" />
              <h3 className="text-lg font-medium text-gray-600 mb-2">
                暂无专项措施需求
              </h3>
              <p className="text-gray-500">
                根据当前跨越点类型和施工方法，未检测到需要特殊专项措施。
                如需配置专项措施，请在上方手动启用相应选项。
              </p>
            </CardContent>
          </Card>
        )}
    </div>
  );
}
